﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Huirui.Cavan.Domain.MainBoundedContext.SearchModule;
using Huirui.Cavan.Domain.MainBoundedContext.StockModule;
using Huirui.Cavan.Domain.Seedwork;
using Huirui.Cavan.Core.Extension;
using Huirui.Cavan.Domain.MainBoundedContext.SystemModule;
using Huirui.Cavan.Application.MainBoundedContext.SystemModule;

namespace Huirui.Cavan.Application.MainBoundedContext.StockModule
{
    public class StockCheckAppService : BaseAppService<StockCheck, string, StockCheckSearch, IStockCheckRepository>, IStockCheckAppService
    {
        private IWareHouseAppService WareHouseAppService { get; set; }
        private IStockAppService StockAppService { get; set; }

        public override BoolGenericResult<StockCheck> AddOrUpdate(StockCheck entity)
        {
            Init();
            this.WareHouseAppService = this.SpringContext.GetObject(StockModuleConst.WAREHOUSEAPPSERVICE) as IWareHouseAppService;
            this.StockAppService = this.SpringContext.GetObject(StockModuleConst.STOCKAPPSERVICE) as IStockAppService;

            BoolGenericResult<StockCheck> result = new BoolGenericResult<StockCheck>();
            if (entity.WareHouse.IsNotNull() && entity.WareHouse.Id.IsNotEmpty())
            {
                entity.WareHouse = this.WareHouseAppService.GetById(entity.WareHouse.Id);
            }
            foreach (StockCheckDetail stockCheckDetail in entity.StockCheckDetails)
            {
                stockCheckDetail.Stock = this.StockAppService.GetById(stockCheckDetail.Stock.Id);
            }

            Employee employee = this.EmployeeAppService.GetSingleBySearch(SearchFactory.CreateEmployeeSearch(SecurityAppService.UserAccount.Id));
            StockManager stockManager = new StockManager(employee);

            IIDGenerateAppService idGenerateAppService = this.SpringContext.GetObject(SystemModuleConst.IDGENERATEAPPSERVICE, new object[] { employee.Corporation }) as IIDGenerateAppService;
            entity.Id = idGenerateAppService.GenerateID(SystemIdentifier.ReceiptCodeRuleType.StockCheck);

            result = stockManager.CheckStock(entity.Id, entity.CheckDate, entity.WareHouse, entity.ProductionNumber, entity.Remark, entity.StockCheckDetails);

            if (result.IsSuccess)
            {
                base.AddOrUpdate(result.Object);
            }

            result.Messages.Add("保存成功");

            return result;
        }
    }
}
